package handler.commandprocessor;

import dao.ClientDAO;
import handler.CommandHandler;
import io.netty.channel.ChannelHandlerContext;
import message.Command;
import message.command.LoginCommand;
import message.receive.LoginReceive;
import route.Router;
import util.Constants;

public class LoginProcessor implements CommandHandler.CommandProcessor
{
    private ClientDAO clientDAO;
    private Router    router;

    public LoginProcessor(ClientDAO clientDAO, Router router)
    {
        this.clientDAO = clientDAO;
        this.router = router;
    }

    @Override
    public void process(Command command, ChannelHandlerContext ctx)
    {
        String       loginName = ((LoginCommand) command).getLoginName();
        String       clientId  = clientDAO.find(loginName);
        LoginReceive receive   = new LoginReceive();
        if (clientId != null)
        {
            ctx.channel().attr(Constants.CLIENT_ID).set(clientId);
            ctx.channel().attr(Constants.CLIENT_NAME).set(loginName);
            receive.setCode((byte) 0);
            receive.setCodeMsg("登录成功");
            router.clientOnline(clientId, ctx.channel());
        }
        else
        {
            receive.setCode((byte) 1);
            receive.setCodeMsg("客户端标识不存在");
        }
        ctx.channel().writeAndFlush(receive);
    }
}
